package com.twohand.admin.Service.wechat;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.twohand.admin.Vo.mp.AccessTokenVo;
import com.twohand.utils.Response.BaseException;
import com.twohand.utils.Response.HttpRequest;
import com.twohand.utils.Response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class MpServiceImpl implements MpService{
    @Value("${wx.mp.appId}")
    String appId;
    @Value("${wx.mp.appSecret}")
    String appSecret;
    Logger log = LoggerFactory.getLogger(MpServiceImpl.class);
    @Override
    public Response code2OpenId(String code) throws JsonProcessingException {
        HttpRequest<AccessTokenVo> httpRequest = new HttpRequest<>();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type=authorization_code";
        url = url.replace("{appId}",appId)
                .replace("{appSecret}",appSecret)
                .replace("{code}",code);
        log.info("获取accessToken的链接:{}",url);
        AccessTokenVo data = httpRequest.get(AccessTokenVo.class,url);
        log.info("请求回来的openId");
        if(data.getErrcode()!=null){
            throw new BaseException(500,data.getErrmsg());
        }
        return new Response(200,"获取成功",data.getOpenid());
//        return data.getOpenid();
    }
}
